package com.MonkWorks.timedormitory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.MonkWorks.clockDTO.User;
import com.MonkWorks.timedormitory.R;
import com.MonkWorks.timedormitoryDB.ItimeProvider;
import com.MonkWorks.timedormitoryDB.TimeDB;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CreateUserActivity extends Activity {
	
	protected static final String CREATEUSERACTIVITY = "CreateUserActivity";
	private Button button_Back;
	private EditText firstName;
	private EditText lastName;
	private EditText password;
	private EditText email;
	private EditText userName;
	private Button create;
	
	//bring in TimeDB
	ItimeProvider timeUser;
	
	private void initComponent(){
		//implement TimeDB
		timeUser = new TimeDB(this);
		firstName = (EditText) findViewById(R.id.etFirstName);
		lastName = (EditText) findViewById(R.id.etLastName);
		password = (EditText) findViewById(R.id.etPassword); 
		email = (EditText) findViewById(R.id.etEmail);
		userName = (EditText) findViewById(R.id.etUsername);
		create = (Button)findViewById(R.id.btnCreate);
		create.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
			//create user...
			CreateUser();
		 
			}

		});
		
		button_Back =(Button)findViewById(R.id.btnBack);
		button_Back.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent BackIntent = new Intent(v.getContext(), AdminToolsActivity.class);
				startActivityForResult(BackIntent, 0);
				//add init components
				
			}
		});
	
 
}

	public void CreateUser(){
		
		//send the new object to the database
		try {
			//get values from screen input
			String firstname = firstName.getText().toString();
			String lastname = lastName.getText().toString();
			String username = userName.getText().toString();
			String passWord = password.getText().toString();
			String mail = email.getText().toString();
			
			//store values to new user object
			User user = new User();
			
			//validate all text fields before saving user
			if( firstName.getText().toString().length() == 0 ) { 
				firstName.setError( "First name is required!" );
			}
			if( lastName.getText().toString().length() == 0 ) { 
				lastName.setError( "Last name is required!" );
			}
			if( userName.getText().toString().length() == 0 )  { 
				userName.setError( "Username is required!" );
			}
			if( password.getText().toString().length() == 0 )  { 
				password.setError( "Password is required!" );
			}
			if( email.getText().toString().length() == 0 ) { 
				email.setError( "Email is required!" );
			}
			if (isEmailValid(email.getText().toString()) == false){
				email.setError( "Must present a valid Email ex. xxxx@xxx.com" );
			}
			else if(firstName.getText().toString().length() != 0 && lastName.getText().toString().length() != 0 &&
					userName.getText().toString().length() != 0	&& password.getText().toString().length() != 0 &&
					email.getText().toString().length() != 0)
			{
			user.setFirstName(firstname);
			user.setLastName(lastname);
			user.setUsername(username);
			user.setPassword(passWord);
			user.setEmail(mail);
			timeUser.saveUser(user);
			popup("User Created");
			//clear the fields to create new user if needed
			clearFields();
			}
		} catch (Exception e) {
			//send an error message to the user
			popup("Unable to save user");
			//log the error
			Log.e(CREATEUSERACTIVITY, "Save User");
		}
	}
	protected void popup(String message) {
		// this is how we make a popup.
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_user);
        initComponent();
    }

    private void clearFields(){
    	//clear fields
		firstName.setText("");
		lastName.setText("");
		password.setText("");
		email.setText("");
		userName.setText("");
    }
    //validates email
    public static boolean isEmailValid(String email) {
        boolean isValid = false;

        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = email;

        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_create_user, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        
        //Logs the user out
        if (item.getItemId() == R.id.Logoff) {
      	  
      	  Intent  MIntent = new Intent(getBaseContext(),LoginActivity.class);
  			startActivityForResult(MIntent, 0);
  			popup("You have logged out");
          return true;
        }


        return (super.onOptionsItemSelected(item));
      }

}
